<template>
  <div class="flex">
    <div class="menus">
      <div class="menu_con">
        <el-button size="small" link @click="onClick('writeEmail', null)"><i class="iconfont icon-edit" />写邮件</el-button>
      </div>
      <SearchCon @search="handlerSearch" />
      <div class="menu-item" v-for="account in folderList" :key="account.id">
        <div @click.stop="handleChangeAccount(account)" :class="{'is-active': curAccount === account.account}" class="menu-item-title hand">
          <div class="title_con">
            <i class="iconfont icon-arrow-down" v-if="account.account === curAccount" />
            <i class="iconfont icon-arrow-right" v-else />
            <span style="margin-left: 3px;">{{ account.account }}</span>
            <span class="unreadNum" v-if="account.account !== curAccount && account.unreadNum">({{ account.unreadNum }})</span>
          </div>
        </div>
        <template v-if="account.account === curAccount">
          <template v-for="(menu, menuIndex) in account.folderList" :key="account.id + menuIndex">
            <OneContextMenu v-if="!menu.children || !menu.children.length" :items="contextMenuItems" :octm-data="menu" class="module">
              <div @click.stop="changeFolder(menu)" :class="{'is-active': isActive(menu, account)}" class="buttons hand">
                <span>{{ menu.folderName }}</span>
                <span class="unreadNum" v-if="menu.unreadNum">({{ menu.unreadNum }})</span>
              </div>
            </OneContextMenu>
            <template v-else>
              <FolderItem :parentItemAccount="account.account" :folderItem="menu" />
            </template>
          </template>
        </template>
      </div>
    </div>
    <!-- @refresh="handlerRefresh" -->
    <EmailMenu :currentMessageId="currentMessageId" ref="emailMenuRef" :searchList="searchList" @setUserBG="setUserBG" @isReadyUpdateFolderNum="isReadyUpdateFolderNum" />
  </div>
</template>
<script lang="ts" setup name="">
import { ref, defineEmits, defineAsyncComponent, nextTick } from 'vue'
import { storeToRefs } from 'pinia';

import api from "/@/api/email/index";
import EmailMenu from '/@/components/emailMenu/index.vue';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores/index';
import { event } from '@tauri-apps/api';
import { invoke } from '@tauri-apps/api/core';
import { emit as emitEvent } from '@tauri-apps/api/event';

const FolderItem = defineAsyncComponent(() => import('/@/components/folder/components/folderItem.vue'));
const SearchCon = defineAsyncComponent(() => import('./searchCon.vue'));
const OneContextMenu = defineAsyncComponent(() => import('/@/components/Common/OneContextMenu.vue'));
event.listen('refreshMenuList', () => {
  handlerRefresh();
});

// Props
const props = defineProps({
  currentMessageId: {
    type: [String, Number],
    default: ''
  },
});

const stores = useEmail(pinia);
const { curAccount, curFolder, accountList } = storeToRefs(stores);
const searchList = ref(undefined);
const emailMenuRef = ref();
const folderList = ref([...accountList.value]);
const setUserBG = (messageId:string, color:string) => emit('setUserBG', messageId, color);
const emit = defineEmits(['onComplate', 'onClick', 'isReadyUpdateFolderNum', 'setUserBG']);

const contextMenuItems = ref([{
    id: 'allRead',
    label: '全部标为已读',
    show: true,
    action: (obj: any) => {
      emitEvent('emial_operate', {
        operate: 'allRead',
        data: obj.octmData
      })
    }
  }, {
    id: 'addFolder',
    label: '新建文件夹',
    show: true,
    action: (obj: any) => {
      emitEvent('emial_operate', {
        operate: 'addFolder',
        data: obj.octmData
      })
    }
  }
])

const  isReadyUpdateFolderNum = () => {
  // console.log('准备更新')
  emit('isReadyUpdateFolderNum');
};

const handlerToSwitchStatus = (status:string, messageId: string) => { 
  console.log('handlerToSwitchStatus1', status, messageId)
  emailMenuRef.value.handlerToSwitchStatus(status, messageId);
};

const changeFolder = (menu:any) => {
  let folderName = menu.folderName;
  if(menu.folderName === '收件箱') {
      folderName = 'INBOX'
  }
  stores.setFolder(folderName);
  stores.setEmailId('');
}

const onClick = (action: string, email: any) => emit('onClick', action, email);

const handleChangeAccount = (item:any) => {
  stores.setAccount(item.account);
  setSign(item.account);
  stores.setEmailId('');
};

const isActive = (item:any, parentItem: any) => {
  let folderName = curFolder.value;
  if(curFolder.value === 'INBOX') {
    folderName = '收件箱'
  }
  return folderName === item.folderName && parentItem.account === curAccount.value;
}

// 获取邮箱签名
const setSign = async (account: string) => {
  const res = await api.email.getSign(account);
  if (res.code === 200) {
    stores.setSign(res.data || '');
  }
};

const assignUnreadNum = (a: folderItem[], b: folderItem[]) => {
  // 遍历数组
  for (let i = 0; i < a.length; i++) {
    const aItem = a[i];
    const bItem = b[i];

    // 如果当前项有 unreadNum，直接赋值
    aItem.unreadNum = bItem.unreadNum;
    // 如果当前项有 children，递归处理
    if (aItem.children && bItem.children) {
      assignUnreadNum(aItem.children, bItem.children);
    }
  }
};

const getFolderList = async () => {
  const params = {
    // account: curAccount.value,
    searchList: searchList.value,
    // box: curFolder.value,
  }
  const res = await api.email.searchEmailBox(params);
  if (res.code === 200) {
    const { emailBoxRes } = res.data;
    const list = Object.keys(emailBoxRes).reverse().map(key => {
      const folderList = emailBoxRes[key].map(item => {
        return {
          folderName: item.box,
          unreadNum: item.num
        }
      });
      return {
        id: key,
        account: key,
        folderList,
      }
    });
    folderList.value = list;
  }
};

const handlerSearch = async (list: any) => {
  if (list.length) {
    searchList.value = list;
    getFolderList();
  } else {
    searchList.value = undefined;
    folderList.value = [...accountList.value];
  }
  
  if (emailMenuRef.value) {
    await nextTick();
    emailMenuRef.value.refresh();
  }
};

const handlerRefresh = () => {
  const account = accountList.value.find(item => item.account === curAccount.value);

  api.email.getUnreadNum(curAccount.value).then((res: any) => {
    if (res.code === 200) {
      const list = res.data;
      if (account?.folderList) {
        assignUnreadNum(account.folderList, list);
        // console.log('list', list);
        // console.log('account.folderList', account.folderList);
        let sum = 0;
        accountList.value.forEach((item: any) => {
          item.unreadNum = item.folderList.reduce((sum: number, folder: any) => {
            return sum + folder.unreadNum;
          }, 0);
          sum = sum + item.unreadNum;
        });
        if (sum > 0) {
          invoke('update_tray_title', { title: sum.toString() });
        }
      }
    }
  });
  
};

setSign(curAccount.value);
defineExpose({handlerRefresh, handlerToSwitchStatus})
</script>
<style lang="scss" scoped>
.menus::-webkit-scrollbar {
  width: 0px; /* 设置滚动条宽度 */
}
.menus {
  width: 200px;
  height: 100%;
  overflow: auto;
  background-color: #f3f4f6;
  border-right: 1px solid #ddd;
  user-select: none;

  .menu-item {
    margin-bottom: 12px;
    margin-top: 5px;
  }

  .module, .menu-item-title {
    position: relative;
    display: flex;
    align-items: center;
    height: 30px;

    .buttons {
      display: flex;
      align-items: center;
      height: 100%;
      padding-left: 23px;
      font-size: 12px;
      width: 100%;
      height: 30px;

      & > span {
        margin-left: 6px;
      }
    }

    &::after {
      position: absolute;
      top: 28px;
      left: 0;
      width: 100%;
      height: 2px;
      content: "";
    }
  }
}
.is-active {
  background: #e6e7e9;
}

.flex {
  display: flex;
}

.unreadNum {
  font-weight: bold;
  margin-left: 3px;
}

.title_con {
  padding: 0 8px;
}

.menu_con {
  padding: 10px;
}

.icon-bianji {
  font-size: 20px;
  cursor: pointer;
}

.icon-edit {
  font-size: 16px;
  margin-right: 5px;
  color: #000;
}
</style>
